package com.lbb.cas;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Stock {
	
	Logger log = LoggerFactory.getLogger(Stock.class);
	private Stock(){}
	
	private static final Stock stock = new Stock();
	private volatile AtomicInteger  count = new AtomicInteger(50);//50
	
	
	AtomicReference<Stock> ar = new AtomicReference<Stock>();
	
	
	CyclicBarrier cyclicBarrier = new CyclicBarrier(50);// 栅栏拦住50个请求
	
	
	public static Stock getStock(){
		return stock;
	}
	
	public void stock(){
		
		try {
			
			log.debug("线程 {}到达栅栏 ,库存:{}.....",Thread.currentThread().getName(),count.get());
			cyclicBarrier.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			e.printStackTrace();
		}
		
		log.debug("50个请求到达，栅栏打开，线程 {},库存:{}。。。。。。。。。",Thread.currentThread().getName(),count.get());
		if (count.get() >0){
			count.decrementAndGet();
			
			log.debug("线程 {} ,库存扣减:{}.....",Thread.currentThread().getName(),count.get());
		}
		
		else {
			log.debug("线程 {}卖光了................",Thread.currentThread().getName());
			
		}
		
		
	}

}
